package com.jdk.learn.juc2.thread;

/**
 * 类功能描述:
 * 重排序问题
 *      在多线程的情况 下，如果write先执行 结果ok read先则ready
 * @author bgt
 * @version V1.0
 * @since 2019-02-01 15:24
 */
public class BaseChongPaiXu {
    private static boolean ready = false;
    private static Integer num = 0;
    private static Integer breaknum = 0;

    /**
     *  error result
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        ReadThread readThread = new ReadThread();
        WriteThread writeThread = new WriteThread();

        readThread.start();
        writeThread.start();
        Thread.sleep(1000);
        readThread.interrupt();
        System.out.println("main exit");
    }

    /**
     *  right result
     * @param args
     * @throws InterruptedException
     */
    public static void main2(String[] args) throws InterruptedException {

        WriteThread writeThread=new WriteThread();
        writeThread.start();
        Thread.sleep(1000);
        ReadThread readThread=new ReadThread();

        readThread.start();
        readThread.join();
        writeThread.join();
        readThread.interrupt();

        System.out.println("main exit");
    }

    static class ReadThread extends Thread {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                if (ready) {
                    System.out.println(num + num);
                }
                System.out.println("read running");
                breaknum++;
                if (breaknum == 10) break;
            }
        }
    }

    static class WriteThread extends Thread {
        @Override
        public void run() {
            num = 2;
            ready = true;
            System.out.println("write running");
        }
    }
}
